<template>
  <el-scrollbar 
    ref="scrollbarRef" 
    height="75vh" 
    class="infinite-scroll-wrapper"
    @scroll="handleScroll"
  >
    <!-- 空状态 -->
    <div v-if="showEmpty" class="empty-tip">
      <slot name="empty">
        <el-empty :description="my_characters ? '你还没有创建过角色' : '暂时没有相关内容'"/>
      </slot>
    </div>

    <!-- 角色网格 -->
    <div v-else class="content-container">
      <div class="card-grid">
        <div 
          v-for="character in characters" 
          :key="character.id" 
          class="card-item"
        >
          <character-card 
            class="pixel-card"
            :character-id="character.id"
            :name="character.name"
            :image_url="character.image_url"
            :show-admin="my_characters"
            @delete-success="handleDeleteSuccess"
          />
        </div>
      </div>

      <!-- 加载状态 -->
      <div class="status-container">
        <div v-if="loading" class="loading-tip">
          <el-icon class="loading-icon">
            <Loading />
          </el-icon>
          <span>加载中...</span>
        </div>
        <div v-if="noMore" class="no-more">
          <div class="pixel-divider">◆◆◆◆◆◆ 已经到底啦 ◆◆◆◆◆◆</div>
        </div>
      </div>
    </div>
  </el-scrollbar>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted, onActivated, nextTick } from 'vue'
import { ElScrollbar, ElIcon, ElEmpty } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import CharacterCard from '@/components/characterCard/index.vue'
import { onBeforeRouteLeave } from 'vue-router'
import { characterAPI } from '@/api/characters'
import { useAuthStore } from '@/stores/authStore'
import { storeToRefs } from 'pinia'

const props = defineProps({
  my_characters: {
    type: Boolean,
    default: false
  }
})

// 认证存储
const authStore = useAuthStore()
const { user } = storeToRefs(authStore)

// 组件状态
const characters = ref<any[]>([])
const cursor = ref<number | null>(null)
const hasMore = ref(true)
const loading = ref(false)
const loadingLock = ref(false)
const pageSize = 10

// 计算属性
const noMore = computed(() => !hasMore.value)
const showEmpty = computed(() => !loading.value && characters.value.length === 0)

// 滚动容器引用
const scrollbarRef = ref<InstanceType<typeof ElScrollbar> | null>(null)
const scrollbarWrapRef = ref<HTMLElement | null>(null)
const rememberScroll = ref(0)

// 初始化滚动容器引用
const initScrollRef = async (retry = 0) => {
  await nextTick()
  if (scrollbarRef.value?.wrapRef) {
    scrollbarWrapRef.value = scrollbarRef.value.wrapRef
  } else if (retry < 3) {
    setTimeout(() => initScrollRef(retry + 1), 100)
  }
}

// 数据加载
const load = async () => {
  if (loadingLock.value || !hasMore.value) return

  loadingLock.value = true
  loading.value = true

  try {
    const authorId = props.my_characters ? user.value?.userId : null
    const res = await characterAPI.listCharacters(
      cursor.value,
      pageSize,
      authorId
    )

    characters.value = [...characters.value, ...res.data.items]
    cursor.value = res.data.next_cursor
    hasMore.value = res.data.has_more
  } catch (error) {
    console.error('加载失败:', error)
    hasMore.value = false
  } finally {
    loading.value = false
    loadingLock.value = false
  }
}

// 重置状态
const resetState = () => {
  characters.value = []
  cursor.value = null
  hasMore.value = true
}

// 滚动处理
const handleScroll = ({ scrollTop }: { scrollTop: number }) => {
  const container = scrollbarWrapRef.value
  if (!container) return

  const { clientHeight, scrollHeight } = container
  const isBottom = scrollHeight - (scrollTop + clientHeight) <= 100

  if (isBottom && !loading.value && hasMore.value) {
    load()
  }
}

const handleDeleteSuccess = (deletedId) => {
  characters.value = characters.value.filter(character => character.id !== deletedId)
}

// 监听模式变化
watch(() => props.my_characters, () => {
  resetState()
  load()
})

// 生命周期
onMounted(async () => {
  await initScrollRef()
  load()
})

onActivated(async () => {
  await initScrollRef()
  if (scrollbarWrapRef.value) {
    scrollbarWrapRef.value.scrollTop = rememberScroll.value
  }
})

onBeforeRouteLeave(() => {
  if (scrollbarWrapRef.value) {
    rememberScroll.value = scrollbarWrapRef.value.scrollTop
  }
})
</script>

<style scoped>
/* 像素风格基础设置 */
.infinite-scroll-wrapper {
  background: #ffffff;
  font-family: 'Press Start 2P', cursive;
}

.content-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 网格布局 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
  padding: 16px 0;
}

/* 卡片样式 */
.pixel-card {
  border: 3px solid #4A342C;
  border-radius: 0;
  background: #FFF9F1;
  box-shadow: 4px 4px 0 rgba(0,0,0,0.15);
  transition: all 0.2s ease;
}

.pixel-card:hover {
  transform: translate(-2px, -2px);
  box-shadow: 6px 6px 0 rgba(0,0,0,0.2);
}

/* 加载状态 */
.status-container {
  margin-top: 20px;
}

.loading-tip {
  text-align: center;
  padding: 24px;
  color: #689F38;
  font-size: 14px;
}

.loading-icon {
  animation: rotating 1.2s linear infinite;
  margin-right: 8px;
}

/* 底部分隔线 */
.pixel-divider {
  color: #795548;
  font-size: 14px;
  text-align: center;
  position: relative;
  padding: 24px 0;
  letter-spacing: 2px;
}

.pixel-divider::before {
  content: "";
  position: absolute;
  left: 20%;
  right: 20%;
  top: 50%;
  height: 2px;
  background: #BCAAA4;
}

/* 空状态 */
.empty-tip {
  padding: 40px 0;
}

/* 动画 */
@keyframes rotating {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式 */
@media (max-width: 768px) {
  .card-grid {
    grid-template-columns: 1fr;
  }
  
  .card-item {
    margin: 0 8px;
  }
}
</style>